package cn.edu.buaa.indexcache;

import java.util.TreeSet;

import cn.edu.buaa.common.IndexCacheConstants;
import cn.edu.buaa.common.IndexCacheException;


public class LeafFileManager {
	
	private int currentMaxPosition = 0;
	private LeafFile[] files = null;
	private TreeSet<Integer> freePositions = null;
	
	private static LeafFileManager manager = null;
	private LeafFileManager() {
		files = new LeafFile[65535];
		freePositions = new TreeSet<Integer>();
	}
	
	public static LeafFileManager getInstance() {
		if (null == manager) {
			manager = new LeafFileManager();
		}
		
		return manager;
	}
	
	public int getAvailableFileNumber() throws IndexCacheException {
		if (0 != freePositions.size()) {
			return freePositions.pollFirst();
		}
		
		if (currentMaxPosition > IndexCacheConstants.MAX_BASE_VALUE) {
			throw new IndexCacheException("currentMaxPosition is out of range");
		}
		
		return currentMaxPosition++;
	}
	
	public void putLeafFile(int pos, LeafFile file) throws IndexCacheException {
		if (null != files[pos]) {
			throw new IndexCacheException(pos + " is illegal because of exist File");
		}
		
		files[pos] = file;
	}
	
	public LeafFile getLeafFile(int pos) throws IndexCacheException {
		if (null == files[pos]) {
			throw new IndexCacheException(pos + " is illegal because of null file");
		}
		
		return files[pos];
	}
	
	public void removeLeafFile(int pos) {
		freePositions.add(pos);
		files[pos] = null;
	}
}
